package org.xyl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.xyl.router.ToolRouter;
import org.xyl.service.McpService;
import java.util.Map;

/**
 * MCP服务器初始化类 - 用于注册工具处理器
 */
@Component
public class McpInitializer implements ApplicationRunner {
    
    @Autowired
    private ToolRouter toolRouter;
    
    @Autowired
    private McpService mcpService;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 注册search_knowledge_base工具
        toolRouter.registerTool("search_knowledge_base", params -> {
            String query = params.getOrDefault("query", "") instanceof String ? (String) params.getOrDefault("query", "") : "";
            String documentType = params.getOrDefault("document_type", "") instanceof String ? (String) params.getOrDefault("document_type", "") : "";
            int maxResults = 5;
            if (params.get("max_results") instanceof Number) {
                maxResults = ((Number) params.get("max_results")).intValue();
            }
            return mcpService.searchKnowledgeBase(query, documentType, maxResults);
        });
        
        // 注册get_device_status工具
        toolRouter.registerTool("get_device_status", params -> {
            String deviceId = params.getOrDefault("device_id", "") instanceof String ? (String) params.getOrDefault("device_id", "") : "";
            return mcpService.getDeviceStatus(deviceId);
        });
        
        // 注册analyze_device_logs工具
        toolRouter.registerTool("analyze_device_logs", params -> {
            String deviceId = params.getOrDefault("device_id", "") instanceof String ? (String) params.getOrDefault("device_id", "") : "";
            String timeRange = params.getOrDefault("time_range", "24h") instanceof String ? (String) params.getOrDefault("time_range", "24h") : "24h";
            return mcpService.analyzeDeviceLogs(deviceId, timeRange);
        });
        
        // 注册create_support_ticket工具
        toolRouter.registerTool("create_support_ticket", params -> {
            String customerId = params.getOrDefault("customer_id", "") instanceof String ? (String) params.getOrDefault("customer_id", "") : "";
            String deviceId = params.getOrDefault("device_id", "") instanceof String ? (String) params.getOrDefault("device_id", "") : "";
            String problemDescription = params.getOrDefault("problem_description", "") instanceof String ? (String) params.getOrDefault("problem_description", "") : "";
            String priority = params.getOrDefault("priority", "中等") instanceof String ? (String) params.getOrDefault("priority", "中等") : "中等";
            return mcpService.createSupportTicket(customerId, deviceId, problemDescription, priority);
        });
        
        System.out.println("MCP工具注册完成！已注册工具数量: 4");
    }
}
